<template>
  <div class="input-box">
    <textarea placeholder="说点什么..." v-model="userMessage" class="textarea" rows="2" @keydown="handleEnterKetToSend"
      maxlength="500"></textarea>

    <div class="send-div">
      <div class="tools">
        <!-- <span class="tool-item" :class="{ active: tools.deepThinking }" @click="toggleTool('deepThinking')">
          <span class="tool-icon">💭</span>
          深度思考
        </span>
        <span class="tool-item" :class="{ active: tools.webSearch }" @click="toggleTool('webSearch')">
          <span class="tool-icon">🌐</span>
          联网搜索
        </span> -->
        <span class="tool-item" :class="{ active: tools.tools }" @click="toggleTool('tools')">
          <span class="tool-icon">🛠️</span>
          搜索范围
        </span>
      </div>

      <div class="send-right">
        <span class="char-counter">{{ userMessage.length }}/500</span>
        <button class="send-btn" @click="handleSend()" :disabled="!userMessage.trim() || sendFlag">
          <span class="send-icon">↵</span>
        </button>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, watch } from 'vue';
import axios from 'axios';
import { fetchEventSource } from '@microsoft/fetch-event-source';

const emits = defineEmits(['update:newSession', 'update:sendFlag']);

const props = defineProps({
  message: {
    type: Boolean,
    default: '',
  },
  sendMessage: {
    type: Function,
    default: () => { },
  },
  createEmptyMessage: {
    type: Function,
    default: () => { },
  },
  updateMessageContent: {
    type: Function,
    default: () => { },
  },
});

const userMessage = ref('');
const sendFlag = ref(false);
const tools = reactive({
  deepThinking: false,
  webSearch: false,
  tools: false
});

watch(() => sendFlag.value, (newVal) => {
  emits('update:sendFlag', newVal);
});

function toggleTool(toolName) {
  tools[toolName] = !tools[toolName];
}

// async function handleSend() {
//   if (sendFlag.value) return;
//   sendFlag.value = true;
//   let userMsg = userMessage.value;
//   if (!userMsg.trim()) return;

//   emits('update:newSession', false);
//   props.sendMessage(userMsg, 'user');
//   userMessage.value = '';

//   const messageId = props.createEmptyMessage('chat');
//   let accumulatedContent = '';

//   try {
//     await fetchEventSource('http://cc:8000/stream', {
//       method: 'POST',
//       headers: {
//         'Content-Type': 'application/json',
//       },
//       body: JSON.stringify({ question: userMsg }),

//       onopen: async (response) => {
//         console.log('连接已建立', response.status);
//         if (response.status === 200) {
//           return;
//         }
//         throw new Error(`连接失败: ${response.status}`);
//       },

//       onmessage: (event) => {
//         if (event.data === '[DONE]') {
//           return;
//         }

//         try {
//           const data = JSON.parse(event.data);
//           if (data.content) {
//             accumulatedContent += data.content;
//             console.log('accumulatedContent', accumulatedContent);

//             props.updateMessageContent(messageId, accumulatedContent);
//           }
//         } catch (e) {
//           console.error('解析错误:', e);
//         }
//       },

//       onclose: () => {
//         console.log('连接关闭');
//         sendFlag.value = false;
//       },

//       onerror: (error) => {
//         console.error('SSE错误:', error);
//         sendFlag.value = false;
//         throw error;
//       }
//     });

//   } catch (error) {
//     console.error('请求失败:', error);
//     sendFlag.value = false;
//   }
// }


async function handleSend(fatherMsg = null) {
  if (sendFlag.value) return
  sendFlag.value = true
  console.log(userMessage.value, fatherMsg);

  let userMsg = userMessage.value
  if (fatherMsg !== null) userMsg = fatherMsg
  if (!userMsg.trim()) return

  emits('update:newSession', false)
  props.sendMessage(userMsg, 'user')
  userMessage.value = ''

  const messageId = props.createEmptyMessage('chat')
  let accumulatedContent = ''
  let pendingChars = []
  let isTyping = false

  function typeNextChar() {
    if (pendingChars.length === 0) {
      isTyping = false
      return
    }
    accumulatedContent += pendingChars.shift()
    props.updateMessageContent(messageId, accumulatedContent)
    setTimeout(typeNextChar, 20) // 每字 20ms（可调）
  }

  try {
    await fetchEventSource('http://cc:8000/stream', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({ question: userMsg }),

      onopen: async (response) => {
        if (response.status === 200) {
          return
        }
        throw new Error(`连接失败: ${response.status}`)
      },

      onmessage: (event) => {
        if (event.data === '[DONE]') {
          return
        }

        try {
          const data = JSON.parse(event.data)
          if (data.content) {
            // 将新内容拆成字符，加入队列
            pendingChars.push(...data.content.split(''))
            // 如果没在打字，启动打字机
            if (!isTyping) {
              isTyping = true
              typeNextChar()
            }
          }
        } catch (e) {
          console.error('解析错误:', e)
        }
      },

      onclose: () => {
        sendFlag.value = false
      },

      onerror: (error) => {
        console.error('SSE错误:', error)
        sendFlag.value = false
        throw error
      }
    })
  } catch (error) {
    console.error('请求失败:', error)
    sendFlag.value = false
  }
}

function handleEnterKetToSend(e) {
  if (e.key === 'Enter' && !e.shiftKey) {
    e.preventDefault();
    handleSend();
  }
}

defineExpose({
  handleSend,
})
</script>

<style scoped lang="scss">
.input-box {
  background-color: white;
  border-radius: 16px;
  padding: 16px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
  border: 1px solid #e8e8e8;
  transition: all 0.3s ease;
  margin-top: 5px;
  display: flex;
  flex-direction: column;
  min-height: calc(100% - 100px);
  box-sizing: border-box;

  &:focus-within {
    box-shadow: 0 4px 25px rgba(0, 120, 212, 0.12);
    border-color: #0078d4;
  }
}

.textarea {
  width: 100%;
  border-radius: 8px;
  padding: 12px;
  border: none;
  outline: none;
  resize: none;
  font-size: 15px;
  line-height: 1.5;
  transition: all 0.3s ease;
  background-color: #ffffff;
  font-family: inherit;
  flex: 1;
  min-height: 60px;
  margin-bottom: 12px;

  &:focus {
    border: none;
    outline: none;
    resize: none;
  }

  &::placeholder {
    color: #a0a0a0;
  }
}

.tools {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 12px;
  flex-wrap: wrap;
}

.tool-item {
  display: flex;
  align-items: center;
  gap: 6px;
  padding: 6px 12px;
  border-radius: 16px;
  cursor: pointer;
  transition: all 0.3s ease;
  font-size: 13px;
  color: #666;
  background-color: #f8f9fa;
  border: 1px solid #e9ecef;
  user-select: none;

  &:hover {
    background-color: #e8f4ff;
    border-color: #0078d4;
    color: #0078d4;
    transform: translateY(-1px);
  }

  &.active {
    background-color: #0078d4;
    color: white;
    border-color: #0078d4;

    .tool-icon {
      filter: brightness(0) invert(1);
    }
  }
}

.tool-icon {
  font-size: 14px;
  transition: all 0.3s ease;
}

.send-div {
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-wrap: wrap;
  gap: 12px;
  margin-top: auto;
}

.send-right {
  display: flex;
  align-items: center;
  gap: 12px;
}

.char-counter {
  font-size: 12px;
  color: #6c757d;
  min-width: 50px;
  text-align: right;
}

.send-btn {
  background: linear-gradient(135deg, #0078d4, #106ebe);
  color: white;
  border: none;
  padding: 8px 14px;
  border-radius: 16px;
  cursor: pointer;
  font-size: 14px;
  font-weight: 500;
  transition: all 0.3s ease;
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 2px 6px rgba(0, 120, 212, 0.3);

  &:hover:not(:disabled) {
    background: linear-gradient(135deg, #106ebe, #005a9e);
    transform: translateY(-1px);
    box-shadow: 0 4px 10px rgba(0, 120, 212, 0.4);
  }

  &:active:not(:disabled) {
    transform: translateY(0);
  }

  &:disabled {
    background: #adb5bd;
    cursor: not-allowed;
    transform: none;
    box-shadow: none;
    opacity: 0.6;
  }
}

.send-icon {
  font-size: 16px;
  font-weight: bold;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .input-box {
    padding: 12px;
    border-radius: 12px;
    min-height: 120px;
  }

  .send-div {
    flex-direction: row;
    align-items: center;
    gap: 8px;
  }

  .tools {
    gap: 6px;
    margin-bottom: 8px;
  }

  .send-right {
    justify-content: flex-end;
    flex: 1;
  }

  .tool-item {
    padding: 4px 8px;
    font-size: 12px;
  }

  .textarea {
    padding: 10px;
    font-size: 14px;
    margin-bottom: 8px;
  }

  .send-btn {
    padding: 6px 12px;
    font-size: 13px;
    min-width: 45px;
  }

  .char-counter {
    font-size: 11px;
    min-width: 45px;
  }
}

/* 小屏幕优化 */
@media (max-width: 480px) {
  .input-box {
    padding: 10px;
  }

  .tools {
    justify-content: center;
  }

  .send-div {
    flex-direction: column;
    align-items: stretch;
    gap: 8px;
  }

  .send-right {
    justify-content: space-between;
  }
}
</style>
